package com.skynet.springboot.mybatis.springmybatis.aspect;

import com.skynet.springboot.mybatis.springmybatis.Exception.CheckException;
import com.skynet.springboot.mybatis.springmybatis.dto.ResultBean;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author Skynet
 * @Date 2017/9/12-20:56.
 */
@Component
@Aspect
public class ControllerAspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(ControllerAspect.class);

    @Pointcut("execution(* com.skynet.springboot.mybatis.springmybatis.controller.*.*(..))")
    public void logPointCut(){}

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint joinPoint) {
        long startTime = System.currentTimeMillis();
        ResultBean<?> result;
        //执行方法
        try {
            result = (ResultBean<?>) joinPoint.proceed();
            //执行时长(毫秒)
            long time = System.currentTimeMillis() - startTime;
            LOGGER.info("{} use time: {}", joinPoint.getSignature(), time);
        } catch (Throwable e) {
            result = handlerException(joinPoint, e);
        }
        return result;
    }

    private ResultBean<?> handlerException(ProceedingJoinPoint joinPoint, Throwable e) {
        ResultBean<?> result = new ResultBean();
        // 已知异常
        if (e instanceof CheckException) {
            result.setMsg(e.getLocalizedMessage());
            result.setCode(ResultBean.FAIL);
        } else {
            LOGGER.error("{} error ", joinPoint.getSignature(), e);
            result.setMsg(e.toString());
            result.setCode(ResultBean.FAIL);
            // 未知异常是应该重点关注的，这里可以做其他操作，如通知邮件，单独写到某个文件等等。
        }
        return result;
    }

}
